package top.xchch.tool.cipher.atguigu;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 代码和 des一样, 密钥长度不一样
 */
public class AESDemo05 {
    public static void main(String[] args) throws Exception{
        // 原文
        String input = "硅谷";
        // 定义key 使用AES进行加密, 密钥必须是16个字节
        String key = "1234567812345678";
        // 算法
        String transformation = "AES";
        // 加密类型
        String algorithm = "AES";
        // 加密
        String encryptDES = encryptDES(input, key, algorithm, transformation);
        System.out.println("加密: " + encryptDES); // 加密: LIdHYmgk7CfTDY/pvc/SlQ==

        // 解密
        String src = decryptDES(encryptDES, key, algorithm, transformation);
        System.out.println("解密: " + src); // 解密: 硅谷
    }

    private static String encryptDES(String input, String key, String algorithm
            , String transformation) throws Exception {
        // 创建加密对象
        Cipher cipher = Cipher.getInstance(transformation);
        // 创建加密规则
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
        // 进行加密初始化
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        // 调用加密方法
        byte[] bytes = cipher.doFinal(input.getBytes());

        return Base64.encode(bytes);
    }

    private static String decryptDES(String encryptDES, String key, String algorithm
            , String transformation) throws Exception {
        Cipher cipher = Cipher.getInstance(transformation);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        // 调用加密方法
        byte[] bytes = cipher.doFinal(Base64.decode(encryptDES));

        return new String(bytes);
    }
}
